package com.wang.common.utils;

import io.jsonwebtoken.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 生成JSON Web令牌的工具类
 */
@Configuration
public class JwtHelper {

    //token过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //加密秘钥
    private static String SECRET_KEY = "123456";

    //根据租户,用户id和用户名称生成token字符串
//    public static String createToken(String tenantId, Long userId, String username) {
//        String token = Jwts.builder()
//                .setSubject("AUTH-USER")
//                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
//                .claim("tenant_id", tenantId)
//                .claim("userId", userId)
//                .claim("username", username)
//                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
//                .compressWith(CompressionCodecs.GZIP)
//                .setIssuedAt(new Date())
//                .compact();
//        return token;
//    }

    //根据租户,用户id和用户名称生成token字符串
    public static String createToken(String tenantId, Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("tenant_id", tenantId)
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                // 取消压缩，生成标准的 JWT
                //.compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }


    // 解析 token
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    // 验证 token 是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

    //从token字符串获取userid
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            // 获取 userId 并进行类型检查和转换
            Object userIdObj = claims.get("userId");
            if (userIdObj instanceof Integer) {
                return ((Integer) userIdObj).longValue(); // 将 Integer 转为 Long
            } else if (userIdObj instanceof Long) {
                return (Long) userIdObj;
            } else {
                return null; // 如果类型不匹配，返回 null
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //从token字符串获取username
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken("100001", 1L, "test");
        System.out.println("token: " + token);

        Long userId = JwtHelper.getUserId(token);
        System.out.println("userId: " + userId);

        String username = JwtHelper.getUsername(token);
        System.out.println("username: " + username);
    }
}